#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import gobject
from lxml import etree as ET
#import xml.etree.ElementTree as ET
from time import time
try:
    import pygtk
    pygtk.require("2.0")
except:
      pass
try:
    import gtk
    import gtk.glade
except:
    print "Error"
    sys.exit(1)
    
class DEFER:
    def __init__(self):
        bench=time()
        self.start=True
        self.xml = gtk.glade.XML('glade.glade')
        #Auto connecting events
        self.xml.signal_autoconnect(self)
        
        
        self.window = self.xml.get_widget('window')
        self.window.connect("delete-event", self.event_quit)
        
        self.vbox=self.xml.get_widget("vbox")
        self.fixed=self.xml.get_widget("fixed")
        self.layout=self.xml.get_widget("layout")
        self.img=self.xml.get_widget("img")
        self.level=self.xml.get_widget("level")
        
        self.heure=self.xml.get_widget("heure")
        self.heureimg=self.xml.get_widget("heureimg")
        self.pression=self.xml.get_widget("pression")
        self.pressionimg=self.xml.get_widget("pressionimg")
        self.temps=self.xml.get_widget("temps")
        self.tempsimg=self.xml.get_widget("tempsimg")
        
        self.maxlevel=150
        
        self.magelis=self.xml.get_widget("magelis")
        self.magelis2=self.xml.get_widget("magelis2")
        
        self.window.show_all()
        
        self.pump=[]
        for i in range(0,6):
            self.pump.append(self.xml.get_widget("pump%s"%(i)))
        print "Loading interface : %s s" %(time()-bench)
        #self.setimg()
        #Loading XML
        bench=time()
        self.file=ET.parse("Synoptique.svg")
        self.parsed=self.file.findall("{http://www.w3.org/2000/svg}g")
        i=1
        self.group=[]
        for node in self.parsed:
            self.group.append(node)
            i=i+1
        self.lavage=False
        self.changeLevel(0.2)
        self.heureimg.hide()
        self.pressionimg.hide()
        self.tempsimg.hide()
        print "Loading xml : %s s" %(time()-bench)
        self.window.maximize()
        self.start=False

    def changeGroupVisibility (self, layer, bool=False, display=False):
            """Layer 2 : Deferisation
            Layer 3 : Lavage 1
            Layer 4 : Lavage 2 
            Layer 5 : Nibeau bas
            Layer 6 : Niveau haut
            Layer 7 : Niveau très haut
            Layer 8 : Niveau déferisation"""
            print "Changing visibility of layer : %s" %(layer)
            if (bool==False):
                if (self.group[layer].attrib.get("style") == "display:inline"):
                    self.group[layer].set("style","display:inline; opacity:0")
                else:
                    self.group[layer].set("style","display:inline")
            else:
                if (display==False):
                    self.group[layer].set("style","display:inline; opacity:0")
                else:
                    self.group[layer].set("style","display:inline")
                    
    def setmagelis (self, text1=None, text2=None):
        if (text1 != None):
            self.magelis.set_text(text1)
        if (text2 != None):
            self.magelis2.set_text(text2)
                
    def deferisation (self):
        if (self.lavage==False):
            if ((self.levelvalue >= 15) and (self.levelvalue <= 97)):
                print "Deferisation !"
                self.setmagelis("Deferisation en cours","")
                self.changeGroupVisibility(2,True,True)
                self.changeGroupVisibility(3,True,False)
                self.changeGroupVisibility(4,True,False)
                self.changePumps(1,True,"gtk-yes")
                self.changePumps(2,True,"gtk-yes")
                self.changePumps(3,True,"gtk-no")
                self.changePumps(4,True,"gtk-no")
                self.changePumps(5,True,"gtk-no")
            else:
                print "Ooops, plus de deferisation !"
                self.setmagelis("Plus de deferisation !","Niveau bas ou haut détecté !")
                self.changeGroupVisibility(2,True,False)
                self.changeGroupVisibility(3,True,False)
                self.changeGroupVisibility(4,True,False)
                self.changePumps(1,True,"gtk-no")
                self.changePumps(2,True,"gtk-no")
                self.changePumps(3,True,"gtk-no")
                self.changePumps(4,True,"gtk-no")
                self.changePumps(5,True,"gtk-no")
            self.loadimg()
    
    def changeLevel (self, value):
        value=1-value
        level=value*self.maxlevel
        self.level.set_fraction(value)
        print level
        for node in self.group[0].findall("{http://www.w3.org/2000/svg}rect"):
            if (node.attrib.get("id") == "rect2381"):
                print "Modifing water level : %s"%(level)
                node.set("height","%s"%(level))
        self.levelvalue=level
        self.deferisation()
        #if (self.level.get_value() != level):
        #    self.level.set_value(level)
        if (level > 133):
            print "Level déversement"
            self.changeGroupVisibility(5,True,True)
            self.changeGroupVisibility(6,True,True)
            self.changeGroupVisibility(7,True,True)
            self.changeGroupVisibility(8,True,True)
        elif ((level <= 133) and (level >= 115)):
            print "Level très haut"
            self.changeGroupVisibility(5,True,False)
            self.changeGroupVisibility(6,True,True)
            self.changeGroupVisibility(7,True,True)
            self.changeGroupVisibility(8,True,True)
        elif ((level < 115) and (level >= 97)):
            print "Level haut"
            self.changeGroupVisibility(5,True,False)
            self.changeGroupVisibility(6,True,False)
            self.changeGroupVisibility(7,True,True)
            self.changeGroupVisibility(8,True,True)
        elif (level >= 30):
            print "Level bas"
            self.changeGroupVisibility(5,True,False)
            self.changeGroupVisibility(6,True,False)
            self.changeGroupVisibility(7,True,False)
            self.changeGroupVisibility(8,True,True)
        elif (level < 30):
            print "LE PLUS BAS !!"
            self.changeGroupVisibility(5,True,False)
            self.changeGroupVisibility(6,True,False)
            self.changeGroupVisibility(7,True,False)
            self.changeGroupVisibility(8,True,False)
            
    def lavage_start (self):
        self.lavage=True
        self.changeGroupVisibility(2,True,False)
        self.changeGroupVisibility(3,True,True)
        self.changeGroupVisibility(4,True,False)
        self.changePumps(1,True,"gtk-no")
        self.changePumps(2,True,"gtk-no")
        self.changePumps(3,True,"gtk-no")
        self.changePumps(4,True,"gtk-yes")
        self.changePumps(5,True,"gtk-no")
        self.setmagelis("Lavage en cours","Supression")
        self.loadimg()
        self.lavage_suite=gobject.timeout_add(10000, self.lavage_continue)
        
    def lavage_continue(self):
        self.changeGroupVisibility(2,True,False)
        self.changeGroupVisibility(3,True,False)
        self.changeGroupVisibility(4,True,True)
        self.changePumps(1,True,"gtk-no")
        self.changePumps(2,True,"gtk-no")
        self.changePumps(3,True,"gtk-yes")
        self.changePumps(4,True,"gtk-no")
        self.changePumps(5,True,"gtk-no")
        self.setmagelis(None,"Lavage")
        self.loadimg()
        self.lavage_end=gobject.timeout_add(10000, self.lavage_finish)
        

    def lavage_finish(self):
        self.lavage=False
        self.heure.set_value(20)
        self.pression.set_value(40)
        self.temps.set_value(0)
        self.deferisation()
        
    def on_heure_changed (self,widget=None,event=None):
        self.heurevalue=widget.get_value()
        if (widget.get_value() >= 23):
            self.heureimg.show()
            if ((self.pressionvalue >= 70) or (self.tempsvalue >= 125)):
                print "Lavage needed !"
                self.lavage_start()
        else:
            self.heureimg.hide()
        
    def on_pression_value_changed (self, widget=None, event=None):
        self.pressionvalue=widget.get_value()
        if (widget.get_value() >= 70):
            if (widget.get_value() >= 23):
                print "Lavage needed !"
                self.lavage_start()
            else:
                self.setmagelis(None,"Défaut détecté, attente 23h")
            self.pressionimg.show()
        else:
            if (self.temps.get_value() < 125):
                self.setmagelis(None,"")
            self.pressionimg.hide()
        
    def on_temps_value_changed (self, widget=None, event=None):   
        self.tempsvalue=widget.get_value()
        if (widget.get_value() >= 125):
            if (widget.get_value() >= 23):
                print "Lavage needed !"
                self.lavage_start()
            else:
                self.setmagelis(None,"Défaut détecté, attente 23h")
            self.tempsimg.show()
        else:
            if (self.pression.get_value() < 70):
                self.setmagelis(None,"")
            self.tempsimg.hide()
            
    def changePumps (self, pump,bool=False,icon="gtk-yes"):
        if (bool==False):
            if (self.pump[pump].get_stock()[0] == "gtk-yes"):
                self.pump[pump].set_from_stock("gtk-no",gtk.ICON_SIZE_BUTTON)
            else:
                self.pump[pump].set_from_stock("gtk-yes",gtk.ICON_SIZE_BUTTON)
        else:
            self.pump[pump].set_from_stock(icon,gtk.ICON_SIZE_BUTTON)
        
    def on_level_button_press_event (self, widget=None, event=None):
        print "Level Value changed"
        mouse_x, mouse_y = event.get_coords()
        progress_loc = widget.get_allocation()
        
        value = mouse_y / progress_loc.height
        
        self.changeLevel(value)
        self.loadimg()
    
    def on_resize(self,widget=None,event=None):
        print "Resize"
        self.loadimg()
        
    def loadimg (self):
        bench=time()
        self.file.write("Synoptique2.svg")
        siz=self.layout.get_allocation()
        #pixbuf = gtk.gdk.pixbuf_new_from_file_at_size("Synoptique2.svg",siz.width,siz.height)
        #self.img.set_from_pixbuf(pixbuf)
        self.img.set_from_file("Synoptique2.svg")
        print "Loading img : %s s" %(time()-bench)
        
    def event_quit (self, widget=None, event=None):
        gtk.main_quit()
        print "Closing.."
        sys.exit(1)

if __name__ == "__main__":
    hwg = DEFER()
    gtk.main()